import json
import os
import time
from typing import Text

import requests
import yaml
from loguru import logger
from xml.etree.ElementTree import ElementTree as ET

class DingDing:
    def __init__(self, webhook):
        self.webhook = webhook
        self.session = requests.session()
        self.session.headers = {"Content-Type": "application/json;charset=utf-8"}

    def Send_MardDown_Msg(self, Content: str, Title: str, atMobiles: list = [], isAtAll: bool = False):
        try:
            data = {
                "msgtype": "markdown",
                "markdown": {
                    "title": Title,
                    "text": Content
                },
                "at": {
                    "atMobiles": atMobiles,
                    "isAtAll": isAtAll
                }
            }

            response = self.session.post(self.webhook, data=json.dumps(data))
            if response.status_code == '200':
                result = {"status": True, "message": "Message has been sent"}
                return result
            else:
                return response.text
        except Exception as error:
            result = {"status": False, "message": f"Failed to send message,Error stack:{error}"}
            return result


def get_report_result():
    import jenkins
    server = jenkins.Jenkins('http://11.164.2.56:8080/', username="anxiaodong", password="An19871103=")
    total = 0
    passd = 0
    faild = 0
    total_time = 0
    path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "config","summary.yml")
    str1 = f"![](https://img.alicdn.com/imgextra/i3/O1CN01Klctpx1nA20et2dwN_!!6000000005048-2-tps-1436-800.png)\n" \
           f"### [接口自动化运行报告]()\n"
    str3 = ""
    print(path)
    for summary in load_yaml_file(path)["report"]:
        print(summary)
        if "summary.json" in summary["path"]:
            with open(summary["path"], 'r', encoding="utf-8") as f:
                res = json.load(f)
                print(res)
                start_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(res['time']['start'] / 1000))
                total = total+int(res['statistic']['total'])
                passd = passd + res['statistic']['passed']
                faild = faild + (res['statistic']['broken'] + res['statistic']['failed'])
                total_time = round(total_time+res['time']['duration']/1000/60, 2)

                str3 = str3 + f"[{summary['name']}]({server.get_job_info(summary['job'])['builds'][0]['url']}allure) **total:**\t{res['statistic']['total']} **pass**: {res['statistic']['passed']} **filed**:  {res['statistic']['broken'] + res['statistic']['failed']}\n" f"*****\n"
                print()
        else:
            tree = ET()
            elements = tree.parse(summary["path"])
            case_pass = elements.find("statistics/total")[1].get("pass")
            passd = passd + int(case_pass)
            case_fail = elements.find("statistics/total")[1].get("fail")
            faild = faild + int(case_fail)
            case_total = int(case_pass) + int(case_fail)
            total = total + int(case_total)
            str3 = str3 + f"[{summary['name']}]({server.get_job_info(summary['job'])['builds'][0]['url']}robot/report/report.html) **total:**\t{case_total} **pass**: {case_pass} **filed**:  {case_fail}\n" f"*****\n"

    str2 = f"> **total:**\t{total} **pass**: {passd} **filed**:  {faild}  **time**: {total_time}m\n ""*****\n"
    con = str1 + str2 + str3
    # dd = DingDing(webhook=os.environ['dingToken'])
    dd_testGroup = DingDing(webhook="https://oapi.dingtalk.com/robot/send?access_token=1442bb79a1d013a4cf5021516c4b945eed85105721d52f97c0409e0b9ced8193")
    # dd.Send_MardDown_Msg(Content=con, Title=os.environ['dingKeyword'])
    os.environ["dingKeyword"] = "接口自动化报告"
    dd_testGroup.Send_MardDown_Msg(Content=con, Title=os.environ['dingKeyword'])
    # dd = DingDing(webhook="https://oapi.dingtalk.com/robot/send?access_token=1442bb79a1d013a4cf5021516c4b945eed85105721d52f97c0409e0b9ced8193")
    # dd.Send_MardDown_Msg(Content=con, Title="接口自动化")


def load_yaml_file(yaml_file: Text):
    """ load yaml file and check file content format
    """
    with open(yaml_file, mode="rb") as stream:
        try:
            yaml_content = yaml.load(stream)
        except yaml.YAMLError as ex:
            err_msg = f"YAMLError:\nfile: {yaml_file}\nerror: {ex}"
            logger.error(err_msg)

        return yaml_content
get_report_result()
